<script setup lang="ts">
import type { FieldVO } from '#/api/config/search/model';
import type { DictData } from '#/api/system/dict/dict-data-model';

import { onMounted, ref } from 'vue';

// import { VbenIcon } from '@vben/icons';
import {
  Input,
  InputNumber,
  RangePicker,
  Select,
  SelectOption,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  AddressCascader,
  CompanySearchInput,
  CompanySearchSelect,
  ExhibitionSelect,
  NumberRangeInput,
} from '#/components/advanced-filter';
import {
  CompanyFavoriteSelect,
  PersonalFavoriteSelect,
} from '#/components/favorite';
import { CompanyTagSelect, PersonalTagSelect } from '#/components/tag';
import { UserListSelect } from '#/components/user-list-select';
import { getDictOptions } from '#/utils/dict';

const props = withDefaults(defineProps<Props>(), {
  fieldNameDisabled: false,
  fieldList: () => [],
  operateList: () => [],
});

const emit = defineEmits(['blur', 'change']);

interface Props {
  fieldNameDisabled?: boolean;
  fieldList?: FieldVO[];
  operateList?: DictData[];
}

const modelValue = defineModel<Record<string, any>>('value', {
  default: () => {
    return {
      fieldName: null,
      fieldLabel: null,
      condition: null,
      value: null,
      exposed: false,
    };
  },
});

// watch(
//   () => modelValue.value,
//   (val) => {
//     console.log('监听value', val);
//     emit('change', modelValue.value);
//   },
//   { deep: true },
// );

const currField = ref<FieldVO>();
const conditionList = ref<any[]>([]);

// watch(
//   () => modelValue.value.fieldName,
//   () => {
//     console.log('触发fieldName watch');
//     setCondition();
//   },
// );

function setCondition() {
  const field = props.fieldList.find(
    (t) => t.fieldName === modelValue.value.fieldName,
  );

  if (field) {
    currField.value = field;
    console.log('setCondition', field);
    modelValue.value.fieldLabel = field.label;
    conditionList.value = field.operates
      ?.split(',')
      .map((op) => {
        const opTarget = props.operateList.find(
          (item) => item.dictValue === op,
        );
        return { label: opTarget?.dictLabel, value: op };
      })
      .filter((v) => v.label);
  }
}

// const fieldList = ref([
//   { label: '字段名1', value: 'customField1' },
//   { label: '字段名2', value: 'customField2' },
//   { label: '字段名3', value: 'customField3' },
//   { label: '字段名4', value: 'customField4' },
// ]);
// const conditionList = ref([
//   { label: '等于', value: 'eq' },
//   { label: '包含', value: 'like' },
//   { label: '不包含', value: 'not' },
// ]);

onMounted(() => {
  // if (props.value) {
  //   modelValue.value = props.value;
  //   emit('change', modelValue.value);
  //
  //   setCondition();
  // }
  setCondition();
  console.log('Condition Filter onMounted:', modelValue.value);
});

function onChange() {
  console.log('condition-filter change', modelValue.value);
  emit('change', modelValue.value);
}

function onFieldNameChange() {
  // console.log('触发onFieldNameChange');
  setCondition();
  // if (conditionList.value?.length > 0 && !modelValue.value.condition) {
  if (conditionList.value?.length > 0) {
    modelValue.value.condition = conditionList.value[0].value;
  }
  onChange();
}

function onConditionChange() {
  onChange();
}
</script>

<template>
  <div class="flex items-center gap-4">
    <slot name="label"></slot>
    <div class="basis-1/4">
      <Select
        v-model:value="modelValue.fieldName"
        placeholder="请选择要筛选的字段名"
        :disabled="fieldNameDisabled"
        class="w-full"
        @blur="emit('blur')"
        @change="onFieldNameChange"
      >
        <SelectOption
          v-for="item in fieldList"
          :key="item.id"
          :value="item.fieldName"
          :disabled="item.disabled"
        >
          {{ item.label }}
        </SelectOption>
      </Select>
    </div>
    <div class="basis-1/6">
      <Select
        v-model:value="modelValue.condition"
        :options="conditionList"
        :disabled="!modelValue.fieldName"
        placeholder="请选择"
        class="w-full"
        @blur="emit('blur')"
        @change="onConditionChange"
      />
    </div>
    <div v-if="currField && modelValue.condition" class="flex-grow">
      <Input
        v-if="currField.component === 'Input'"
        v-model:value="modelValue.value"
        placeholder="请输入"
        :disabled="!modelValue.fieldName"
        class="w-full"
        @blur="emit('blur')"
        @change="onChange"
      />
      <Select
        v-if="currField.component === 'Select'"
        v-model:value="modelValue.value"
        :options="getDictOptions(currField.defaultValue)"
        :disabled="!modelValue.fieldName"
        placeholder="请选择"
        class="w-full"
        @blur="emit('blur')"
        @change="onChange"
      />
      <InputNumber
        v-if="currField.component === 'InputNumber'"
        v-model:value="modelValue.value"
        :min="0"
        placeholder="请输入"
        class="w-full"
        @blur="emit('blur')"
        @change="onChange"
      />
      <RangePicker
        v-if="currField.component === 'RangePicker'"
        v-model:value="modelValue.value"
        class="w-full"
        :placeholder="['开始时间', '结束时间']"
        :show-time="{
          hideDisabledOptions: true,
          defaultValue: [
            dayjs('00:00:00', 'HH:mm:ss'),
            dayjs('23:59:59', 'HH:mm:ss'),
          ],
        }"
        value-format="YYYY-MM-DD HH:mm:ss"
        @blur="emit('blur')"
        @change="onChange"
      />
      <UserListSelect
        v-if="currField.component === 'UserListSelect'"
        v-model:value="modelValue.value"
        @change="onChange"
      />
      <AddressCascader
        v-if="currField.component === 'AddressCascader'"
        v-model:value="modelValue.value"
        change-on-select
        @change="onChange"
      />
      <CompanyTagSelect
        v-if="currField.component === 'CompanyTagSelect'"
        v-model:value="modelValue.value"
        :show-op="false"
        @change="onChange"
      />
      <PersonalTagSelect
        v-if="currField.component === 'PersonalTagSelect'"
        v-model:value="modelValue.value"
        :show-op="false"
        @change="onChange"
      />
      <CompanyFavoriteSelect
        v-if="currField.component === 'CompanyFavoriteSelect'"
        v-model:value="modelValue.value"
        @change="onChange"
      />
      <PersonalFavoriteSelect
        v-if="currField.component === 'PersonalFavoriteSelect'"
        v-model:value="modelValue.value"
        @change="onChange"
      />
      <CompanySearchInput
        v-if="currField.component === 'CompanySearchInput'"
        v-model:value="modelValue.value"
        @change="onChange"
      />
      <CompanySearchSelect
        v-if="currField.component === 'CompanySearchSelect'"
        v-model:value="modelValue.value"
        @change="onChange"
      />
      <ExhibitionSelect
        v-if="currField.component === 'ExhibitionSelect'"
        v-model:value="modelValue.value"
        @change="onChange"
      />
      <NumberRangeInput
        v-if="currField.component === 'NumberRangeInput'"
        v-model:value="modelValue.value"
        @change="onChange"
      />
    </div>
    <slot name="append"></slot>
  </div>
</template>
